package com.liaoyin.travel.scheduling;


import com.liaoyin.travel.view.moble.task.TimedTaskView;
import com.liaoyin.travel.vo.task.InsertTaskVo;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.config.ThreadPoolConfig;
import com.liaoyin.travel.dao.UsersMapper;
import com.liaoyin.travel.dao.task.TaskLineMapper;
import com.liaoyin.travel.dao.task.TimingTaskParameterMapper;
import com.liaoyin.travel.entity.task.Task;
import com.liaoyin.travel.entity.task.TaskLine;
import com.liaoyin.travel.entity.task.TimingTaskSpecificReleaseTime;
import com.liaoyin.travel.service.attendance.AttendanceStatisticsService;
import com.liaoyin.travel.service.task.TaskService;
import com.liaoyin.travel.service.task.TaskTimingService;
import com.liaoyin.travel.service.task.TimingTaskParameterService;
import com.liaoyin.travel.service.task.TimingTaskSpecificReleaseTimeService;
import com.liaoyin.travel.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;


@Component
@EnableScheduling
@PropertySource("classpath:com/liaoyin/travel/scheduling/scheduling.properties")
public class TaskSchedule {

    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    @Resource
    private TaskLineMapper taskLineMapper;
    @Autowired
    private TaskService taskService;
    @Autowired
    private AttendanceStatisticsService attendanceStatisticsService;
    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private TaskTimingService taskTimingService;
    @Autowired
    private TimingTaskSpecificReleaseTimeService timingTaskSpecificReleaseTimeService;
    @Autowired
    TimingTaskParameterService timingTaskParameterService;
    @Resource
    private TimingTaskParameterMapper timingTaskParameterMapper;

    private Log logger = LogFactory.getLog(getClass());

    /*@Value("${api.cms.taisiya.system.url}")
    private String apiCmsStatsSystemUrl;
    @Value("${api.cms.taisiya.news.url}")
    private String apiCmsStatsNewsUrl;*/

    //每日任务领取调用开始运行
    @Scheduled(cron = "${scheduling.oneday}")
    public void getStatsSystem() {
        logger.info("开始运行");
        threadPoolConfig.getThreadPool().execute(() -> {
            taskService.automaticCollectionTask();
        });
    }

    @Scheduled(cron = "${scheduling.oneWeek}")
    public void deleteNULLline() {
        Example example = new Example(TaskLine.class);
        example.and().andIsNull("lineName");
        int i = taskLineMapper.deleteByExample(example);
        logger.info("已删除" + i + "条临时路线");

    }

    /**
     * 　* @description: TODO  每日定时考勤统计
     * 　* @param []
     * 　* @return void
     * 　* @throws
     * 　* @author privatePanda777@163.com
     * 　* @date 2019/9/2 09:37
     *
     *//*
    @Scheduled(cron = "${scheduling.day}")
    public void timedStatisticalAttendance() {
        List<UserInfo> userInfos = this.usersMapper.selectUserInfoList();
        for (UserInfo userInfo : userInfos) {
            this.attendanceStatisticsService.insertAttendanceStatistics(userInfo);
        }
    }*/

    /**
     * @方法名：performScheduledTasks
     * @描述： 每一分钟执行一次定时任务
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/26 15:57
     */
    @Scheduled(cron = "${timedTask.execute}")
    @Transactional(rollbackFor = Exception.class)
    public void performScheduledTasks() {

        System.out.println("------执行定时任务---------");
        //查询到今天要执行的却还未执行的定时任务
        String weekDay = DateUtil.getWeekOfDateStr(new Date());
        List<TimedTaskView> list = this.timingTaskParameterService.selectTimingTaskViewByWeekDay(weekDay);
        if (list.isEmpty()) {
            System.err.println("没有查询到今天要执行的定时任务");
        } else {
            System.err.println("今天要执行的>=当前时间的定时任务有:" + list.size() + "条");
            System.err.println("当前【时:分】：" + DateUtil.dateShiftHhmm(new Date()));
            list.forEach(timedTaskView -> {
                System.err.println("timedTaskView.getUserId()=" + timedTaskView.getUserId());
                Task task = new Task();
                //任务名称
                task.setTaskName(timedTaskView.getTaskName());
                //任务类型
                task.setTaskType(timedTaskView.getTaskType());
                //任务级别
                task.setTaskLevel(timedTaskView.getTaskLevel());
                //任务类别
                task.setTaskCategories(timedTaskView.getTaskCategories());
                //任务说明
                task.setTaskStatement(timedTaskView.getTaskStatement());
                //任务发布人id
                task.setUserId(timedTaskView.getUserId());
                //线路id
                task.setLineId(timedTaskView.getLineId());
                //纬度
                task.setTaskLat(timedTaskView.getTaskLat());
                //经度
                task.setTaskLog(timedTaskView.getTaskLog());
                //是否指定人员
                task.setIsSpecify(timedTaskView.getIsSpecify());
                //单位id
                task.setScenicId(timedTaskView.getScenicId());

                //新增任务要传入vo
                InsertTaskVo insertTaskVo = new InsertTaskVo();
                insertTaskVo.setBusinessId(timedTaskView.getBusinessId());
                insertTaskVo.setTask(task);
                //如果执行的时间和当前时间相等
                String pubTime = timedTaskView.getPubTime();
                System.err.println("pubTime=" + pubTime);

                if (pubTime.equals(DateUtil.dateShiftHhmm(new Date()))) {
                    System.err.println("---新增定时任务-----");
                    //新增任务
                    this.taskService.insertTaskTime(insertTaskVo);
                    //新增定时任务的发布记录
                    TimingTaskSpecificReleaseTime timingTaskSpecificReleaseTime = new TimingTaskSpecificReleaseTime()
                            //定时任务参数id
                            .setTimingTaskParameterId(timedTaskView.getTimedTaskId())
                            //具体的发布时间
                            .setSpecificReleaseTime(new Date())
                            //今天是星期几发的
                            .setWeeNum(LocalDate.now().getDayOfWeek().getValue())
                            //单位id
                            .setScenicId(timedTaskView.getScenicId());
                    this.timingTaskSpecificReleaseTimeService.insertTimingTaskSpecificReleaseTime(timingTaskSpecificReleaseTime);
                }
            });
        }
    }

    /**
     * @return
     * @author 王海洋
     * @methodName: 定时临时任务
     * @methodDesc:
     * @description:
     * @param:
     * @create 2019-12-05 14:26
     **/
    @Scheduled(cron = "${timedTask.execute}")
    @Transactional(rollbackFor = Exception.class)
    public void performTempTasks() {
        System.out.println("------执行临时定时任务---------");
        //查询到今天要执行的却还未执行的定时任务
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time = sdf.format(new Date());
        List<TimedTaskView> list = this.timingTaskParameterService.selectTimingTaskViewNow(time);
        if (list.isEmpty()) {
            System.err.println("没有查询到今天要执行的临时定时任务");
            return;
        } else {
            System.err.println("今天要执行的>=当前时间的定时任务有:" + list.size() + "条");
            System.err.println("当前【时:分】：" + DateUtil.dateShiftHhmm(new Date()));
            list.forEach(timedTaskView -> {
                System.err.println("timedTaskView.getUserId()=" + timedTaskView.getUserId());
                Task task = new Task();
                //任务名称
                task.setTaskName(timedTaskView.getTaskName());
                //任务类型
                task.setTaskType(timedTaskView.getTaskType());
                //任务级别
                task.setTaskLevel(timedTaskView.getTaskLevel());
                //任务类别
                task.setTaskCategories(timedTaskView.getTaskCategories());
                //任务说明
                task.setTaskStatement(timedTaskView.getTaskStatement());
                //任务发布人id
                task.setUserId(timedTaskView.getUserId());
                //线路id
                task.setLineId(timedTaskView.getLineId());
                //纬度
                task.setTaskLat(timedTaskView.getTaskLat());
                //经度
                task.setTaskLog(timedTaskView.getTaskLog());
                //是否指定人员
                task.setIsSpecify(timedTaskView.getIsSpecify());
                task.setPublishType(timedTaskView.getPublishType());
                task.setPublishTime(timedTaskView.getPubTime());

                //景区id
                task.setScenicId(timedTaskView.getScenicId());

                //新增任务要传入vo
                InsertTaskVo insertTaskVo = new InsertTaskVo();
                insertTaskVo.setBusinessId(timedTaskView.getBusinessId());
                insertTaskVo.setTask(task);
                //如果执行的时间和当前时间相等
                String pubTime = timedTaskView.getPubTime();
                System.err.println("临时定时任务---pubTime=" + pubTime);

                //新增任务
                this.taskService.insertTaskTime(insertTaskVo);
                //删除临时定时任务相关参数
                //this.timingTaskParameterService.delTempTaskParam(timedTaskView.getTimedTaskId());
                //新增定时任务的发布记录
                TimingTaskSpecificReleaseTime timingTaskSpecificReleaseTime = new TimingTaskSpecificReleaseTime()
                        //定时任务参数id
                        .setTimingTaskParameterId(timedTaskView.getTimedTaskId())
                        //具体的发布时间
                        .setSpecificReleaseTime(new Date())
                        //今天是星期几发的
                        .setWeeNum(LocalDate.now().getDayOfWeek().getValue())
                        //景区id
                        .setScenicId(timedTaskView.getScenicId());
                this.timingTaskSpecificReleaseTimeService.insertTimingTaskSpecificReleaseTime(timingTaskSpecificReleaseTime);
            });
        }
    }
}
